const express = require("express")//路由属于express 需要先导入express
const router = express.Router()
// npm i jsonwebtoken
const jwt = require('jsonwebtoken')
// 密钥
const key = 'my-key'
// token有效期
const option = {
  expiresIn: '1h' //有效期为1h
}
// 连接数据库
var mysql = require('mysql');
var pool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',//服务器地址
  user: 'root',//用户名
  password: '123456',//密码
  database: 'demo'//数据库名
});

// 
// post登录
router.post("/login", (req, res) => {
  pool.getConnection(function (err, connection) {
    if (err) throw err;// not connected!

    // Use the connection
    // *查询所有字段
    // limit 1查询一条
    connection.query('SELECT * FROM user where username = ? and password = ? limit 1', [req.body.username, req.body.password], function (error, results, fields) {
      // When done with the connection, release it.
      console.log("result", results);
      connection.release();
      if (results.length > 0) {
        // 用户名和密码正确
        // 生成token
        const token = jwt.sign({ id: results[0].id }, key, option)
        //  解析token
        const jie = jwt.verify(token, key)
        console.log(jie, '解析完的token')
        res.status(200)
        res.send({ 'msg': '操作成功', 'data': results, 'token': token, 'code': 200 })
      } else {
        // 用户名或密码错误
        res.status(200)
        res.send({ 'msg': "用户名或密码错误", 'code': 200 })
      }

      // Handle error after the release.
      // connection.release()
      if (error) throw error;

      // Don't use the connection here, it has been returned to the pool.
    });
  });
})

// post注册
router.post("/register", (req, res) => {
  pool.getConnection(function (err, connection) {
    if (err) throw err;// not connected!

    // Use the connection
    // *查询所有字段
    // limit 1查询一条
    connection.query('INSERT INTO `user`(`username`, `password`) VALUES ( ?, ?);', [req.body.username, req.body.password], function (error, results, fields) {
      // When done with the connection, release it.
      connection.release();
      console.log("result", results);


      // Handle error after the release.
      // connection.release()
      if (error) throw error;

      // Don't use the connection here, it has been returned to the pool.
    });
  });
})


module.exports = router